import 'dart:async';

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/core/model/live_room_model.dart';
import 'package:flutter_bilibili/core/model/online_gold_rank_model.dart';
import 'package:flutter_bilibili/core/service/request/live_room_play_request.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:video_player/video_player.dart';

import '../../../core/model/live_rooms_model.dart';
import '../../shared/app_theme.dart';
import 'live_dan_mu.dart';

class HYLiveRoomPlayContent extends StatefulWidget {
  LiveRoomModel liveRoomData;

  HYLiveRoomPlayContent(this.liveRoomData);

  @override
  State<HYLiveRoomPlayContent> createState() => _HYLiveRoomPlayContentState();
}

class _HYLiveRoomPlayContentState extends State<HYLiveRoomPlayContent> {
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  bool isLoadingAccomplished = false;
  late Timer _timer;

  String userName = "获取中...";
  String userFace = "";
  int onlineNum = 0;
  List<OnlineRankItem> top4UserFace = [];
  String watchedShow = "0人看过";

  @override
  void initState() {
    ///顶部状态蓝颜色
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.black);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

    ///每隔一段时间获取实时人气
    _timer = Timer.periodic(Duration(seconds: 5), (t) {
      ///请求直播间基本信息,主播基本信息
      HYLiveRoomPlayRequest.getInfoByLiveRoomData(widget.liveRoomData.roomid)
          .then((value) {
        userName = value.anchorInfo.baseInfo.uname;
        userFace = value.anchorInfo.baseInfo.face;
        watchedShow = value.watchedShow.textLarge;
        if (mounted) {
          setState(() {});
        }
      });

      ///前四高能榜
      HYLiveRoomPlayRequest.getOnlineGoldRankData(
              widget.liveRoomData.upId, widget.liveRoomData.roomid, 1, 4)
          .then((value) {
        onlineNum = value.onlineNum;
        top4UserFace.addAll(value.onlineRankItem);
        if (mounted) {
          setState(() {});
        }
      });
    });

    ///请求直播间基本信息,主播基本信息
    HYLiveRoomPlayRequest.getInfoByLiveRoomData(widget.liveRoomData.roomid)
        .then((value) {
      userName = value.anchorInfo.baseInfo.uname;
      userFace = value.anchorInfo.baseInfo.face;
      watchedShow = value.watchedShow.textLarge;
      if (mounted) {
        setState(() {});
      }
    });

    ///前四高能榜
    HYLiveRoomPlayRequest.getOnlineGoldRankData(
            widget.liveRoomData.upId, widget.liveRoomData.roomid, 1, 4)
        .then((value) {
      onlineNum = value.onlineNum;
      top4UserFace.addAll(value.onlineRankItem);
      if (mounted) {
        setState(() {});
      }
    });

    ///请求视频直播
    HYLiveRoomPlayRequest.getLiveRoomStreamData(widget.liveRoomData.roomid)
        .then((value) {
      ///线路一
      _videoPlayerController = VideoPlayerController.network(value.durl[0].url);
      _videoPlayerController.initialize().then((value) {
        _chewieController = ChewieController(
          autoPlay: true,
          videoPlayerController: _videoPlayerController,
          isLive: true,
          allowMuting: false,
        );
        isLoadingAccomplished = true;
        if (mounted) {
          setState(() {});
        }
      });
    });
    super.initState();
  }

  @override
  void dispose() {
    _timer.cancel();
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Column(
          children: [
            buildLiveRoomPlayAppBarTitle(),
            buildLiveRoomPlayRanking(),
            SizedBox(
              height: 10.px,
            ),
            buildLiveRoomPlayLivePlayer(),
            Expanded(
              child: buildLiveRoomPlayLiveDanMuPanel(),
            ),
          ],
        ),
        bottomNavigationBar: buildLiveRoomPlayBottomSendDanMu(),
      ),
    );
  }

  ///顶部的appBar的内容
  Widget buildLiveRoomPlayAppBarTitle() {
    return Container(
      color: Colors.black,
      height: 70.px,
      padding: EdgeInsets.symmetric(horizontal: 20.px, vertical: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            child: Image.asset(
              ImageAssets.biliPlayerBackButtonPNG,
              width: 20.px,
              height: 20.px,
            ),
            padding: EdgeInsets.only(top: 5.px, right: 5.px, bottom: 5.px),
          ),
          userFace.isEmpty
              ? CircleAvatar(
                  radius: 15.px,
                  backgroundImage: AssetImage(
                    ImageAssets.icRecommendAvatarPNG,
                  ),
                )
              : CircleAvatar(
                  radius: 15.px,
                  backgroundImage: NetworkImage(
                    userFace,
                  ),
                ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 2.px),
            width: 60.px,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  userName,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      fontSize: HYAppTheme.xxSmallFontSize,
                      color: Colors.white),
                ),
                Text(
                  watchedShow,
                  style: TextStyle(
                      fontSize: HYAppTheme.xxxSmallFontSize,
                      color: Colors.white),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.px, horizontal: 16.px),
            decoration: BoxDecoration(
                color: Color.fromRGBO(255, 154, 184, 1),
                borderRadius: BorderRadius.all(Radius.circular(20.px))),
            child: Text(
              "+关注",
              style: TextStyle(
                  fontSize: HYAppTheme.xxSmallFontSize, color: Colors.white),
            ),
          ),
          SizedBox(
            width: 10.px,
          ),
          Expanded(
            child: Stack(
              alignment: Alignment.centerLeft,
              children: top4UserFace.isNotEmpty
                  ? buildTop4User(top4UserFace)
                  : buildTop4UserBg(top4UserFace),
            ),
          ),
          Container(
            padding: EdgeInsets.only(left: 10.px),
            child: Image.asset(
              ImageAssets.videoPlayerMoreCustomPNG,
              width: 20.px,
              height: 20.px,
            ),
          ),
        ],
      ),
    );
  }

  List<Widget> buildTop4User(List<OnlineRankItem> top4UserFace) {
    List<Widget> _widgets = [];
    int leftDistance = 75;
    int i = 0;
    for (var item in top4UserFace) {
      _widgets.add(
        Positioned(
          left: leftDistance.px,
          child: CircleAvatar(
            radius: 15.px,
            backgroundImage: NetworkImage(top4UserFace[i].face),
          ),
        ),
      );
      leftDistance -= 25;
      i++;
    }
    _widgets.add(buildTop4UserLastWidget());
    return _widgets;
  }

  List<Widget> buildTop4UserBg(List<OnlineRankItem> top4UserFace) {
    List<Widget> _widgets = [];
    int leftDistance = 75;
    for (var item in top4UserFace) {
      _widgets.add(
        Positioned(
          left: leftDistance.px,
          child: CircleAvatar(
            radius: 18.px,
            backgroundImage: AssetImage(ImageAssets.icRecommendAvatarPNG),
          ),
        ),
      );
      leftDistance -= 25;
    }
    _widgets.add(buildTop4UserLastWidget());
    return _widgets;
  }

  Widget buildTop4UserLastWidget() {
    return Positioned(
      right: 0,
      child: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [Colors.black.withOpacity(.7), Colors.black],
        )),
        padding: EdgeInsets.symmetric(vertical: 20.px, horizontal: 13.px),
        child: Center(
          child: Text(
            onlineNum.toString(),
            style: TextStyle(
                color: Colors.white, fontSize: HYAppTheme.xxSmallFontSize),
          ),
        ),
      ),
    );
  }

  Widget buildLiveRoomPlayAppBarActions() {
    return Image.asset("assets/image/icon/video_more.png",
        width: 15.px, height: 15.px);
  }

  Widget buildLiveRoomPlayAppBarLeading() {
    return Image.asset(
      "assets/image/icon/bili_player_back_button.png",
      width: 15.px,
      height: 15.px,
    );
  }

  Widget buildLiveRoomPlayLivePlayer() {
    return Container(
      color: Colors.black,
      height: 250.px,
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 10.px, horizontal: 5.px),
      child: isLoadingAccomplished == true
          ? AspectRatio(
              aspectRatio:
                  _chewieController.videoPlayerController.value.aspectRatio,
              child: Chewie(controller: _chewieController),
            )
          : Center(
              child: Container(
                width: 40.px,
                height: 40.px,
                child: CircularProgressIndicator(
                  color: HYAppTheme.norTextColors,
                ),
              ),
            ),
    );
  }

  Widget buildLiveRoomPlayLiveDanMuPanel() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 30.px),
      child: LiveDanMuScreen(widget.liveRoomData.roomid),
    );
  }

  Widget buildLiveRoomPlayBottomSendDanMu() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 10.px),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Container(
            height: 30.px,
            width: 30.px,
            child: CircleAvatar(
              backgroundImage: AssetImage(ImageAssets.icRecommendAvatarPNG),
            ),
          ),
          Container(
            width: 200.px,
            height: 35.px,
            padding: EdgeInsets.symmetric(horizontal: 15.px),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(.3),
              borderRadius: BorderRadius.all(
                Radius.circular(30.px),
              ),
            ),
            child: TextField(
              showCursor: true,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "发个弹幕~",
                hintStyle: TextStyle(
                    color: Colors.white.withOpacity(.5),
                    fontSize: HYAppTheme.xxSmallFontSize),
              ),
            ),
          ),
          CircleAvatar(
            radius: 15.px,
            backgroundColor: Colors.black,
            backgroundImage: AssetImage(ImageAssets.facePNG),
          ),
          CircleAvatar(
            radius: 15.px,
            backgroundColor: Colors.black,
            backgroundImage: AssetImage(ImageAssets.hotActivityPNG),
          ),
          CircleAvatar(
            radius: 15.px,
            backgroundColor: Colors.black,
            backgroundImage: AssetImage(ImageAssets.giftPNG),
          ),
        ],
      ),
    );
  }
}

Widget buildLiveRoomPlayRanking() {
  return Container(
    padding: EdgeInsets.only(left: 20.px),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.symmetric(
            vertical: 5.px,
            horizontal: 12.px,
          ),
          child: Text(
            "热门榜 >",
            style: TextStyle(
              color: Colors.white,
              fontSize: HYAppTheme.xxxSmallFontSize,
            ),
          ),
          decoration: BoxDecoration(
              color: Color.fromRGBO(133, 61, 83, 1),
              borderRadius: BorderRadius.all(Radius.circular(20.px))),
        ),
      ],
    ),
  );
}
